package agent_store

import (
	"context"
	"encoding/json"
	"xialou_platform/app/respx"
	"xialou_platform/services/agent/rpc/agentClient"

	"xialou_platform/services/agent/api/internal/svc"
	"xialou_platform/services/agent/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type StoreDetailLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewStoreDetailLogic(ctx context.Context, svcCtx *svc.ServiceContext) StoreDetailLogic {
	return StoreDetailLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *StoreDetailLogic) StoreDetail(req *types.StoreDetailReq) (resp *types.StoreBody, err error) {
	storeLog, err := l.svcCtx.AgentRpc.StoreLogLatestByStoreId(l.ctx, &agentClient.IdBody{
		Id: respx.IDParse(req.Id).GetInt64(),
	})
	if err != nil {
		return nil, err
	}
	resp = &types.StoreBody{}
	err = json.Unmarshal([]byte(storeLog.Body), &resp)
	resp.Id = respx.IDFrom(storeLog.StoreId).ToString()
	resp.StoreId = respx.IDFrom(storeLog.StoreId).ToString()
	if err != nil {
		return nil, err
	}

	store, err := l.svcCtx.AgentRpc.StoreById(l.ctx, &agentClient.IdBody{
		Id: respx.IDParse(req.Id).GetInt64(),
	})
	if err != nil {
		return nil, err
	}
	resp.FirstPass = store.FirstPass
	return resp, nil
}
